package com.yidu.dao;

import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.util.StringUtils;

import com.yidu.domain.User;
import com.yidu.utils.Pages;

public class UserDaoImpl implements UserDao{
	private HibernateTemplate hibernateTemplate;
	
	public HibernateTemplate getHibernateTemplate() {
		return hibernateTemplate;
	}
	
	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}
	
	@Override
	public void add(User user) {
		hibernateTemplate.save(user);
	}

	@Override
	public void delete(String id) {
		User user = findById(id);
		hibernateTemplate.delete(user);
	}

	@Override
	public void update(User user) {
		hibernateTemplate.clear();
		hibernateTemplate.update(user);
	}

	@Override
	public List<User> findAll(User user, Pages pages) {
		DetachedCriteria criteria = DetachedCriteria.forClass(User.class);
		if(!StringUtils.isEmpty(user.getUserName())) {
			criteria.add(Restrictions.ilike("userName", "%"+user.getUserName()+"%"));
		}
		List<User> list  = (List<User>) hibernateTemplate.findByCriteria(criteria,pages.getStartRows(),pages.getLimit());
		return list;
	}
	/**
	 * 根据id查询
	 */
	@Override
	public User findById(String id) {
		return hibernateTemplate.get(User.class, id);
	}
	/**
	 * 获取行数
	 */
	@Override
	public Long count(User user) {
		DetachedCriteria criteria= DetachedCriteria.forClass(User.class);
		if(!StringUtils.isEmpty(user.getUserName())) {
			criteria.add(Restrictions.ilike("userName", "%"+user.getUserName()+"%"));
		}
		criteria.setProjection(Projections.rowCount());
		Long count = (Long)hibernateTemplate.findByCriteria(criteria).get(0);
		return count;
	}

	@Override
	public List<User> findAllUser(User user) {
		DetachedCriteria criteria = DetachedCriteria.forClass(User.class);
		if(!StringUtils.isEmpty(user.getUserName())) {
			criteria.add(Restrictions.ilike("userName", ""+user.getUserName()+""));
		}
		if(!StringUtils.isEmpty(user.getUserPwd())) {
			criteria.add(Restrictions.ilike("userPwd", ""+user.getUserPwd()+""));
		}
		List<User> list = (List<User>) hibernateTemplate.findByCriteria(criteria);
		return list;
	}
}
